//
//  GasViewController.m
//  FuelLog
//
//  Created by Pure Mass Communications on 9/1/08.
//  Copyright 2008 . All rights reserved.
//
//  Placed under GPL v2 with the kind permission of Pure Mass Communications
//  and modified to make compile under SDK 3.1 by Olaf Greck in May 2010
//
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version 2
//  of the License, or (at your option) any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software
//  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#import "DateViewController.h"
#import "FuelLogAppDelegate.h"
#import "FuelLogViewController.h"
#import "GasViewController.h"


#define kTabBarHeight 20
#define kKeyboardAnimationDuration 0.3

#define _kFuel 0
#define _kCost 1
#define _kUnit 2

@interface GasViewController (PrivateMethods)  
- (void)alertFail:(NSString *)error;

@end

#pragma mark -
@implementation GasViewController

@synthesize scrollView;
@synthesize gas;
//, navItem, 
@synthesize doneButton; 
@synthesize dateButton, deleteButton;
@synthesize odometerBox, fuelLabel, fuelBox, costBox, unitCostText, unitCostBox, fullTankSwitch;
@synthesize fuelVolumeChangedButton, costChangedButton, unitCostChangedButton;
@synthesize roundRobinDictionary;
@synthesize accessCounterFuelBox, accessCounterCostBox, accessCounterUnitCostBox;
@synthesize keyboardSize;
@synthesize isOkToUpdate, askingButtonsAreHidden, areUpdatesPending;
@synthesize activeField;

#pragma mark -

#pragma mark UIAlertView

- (void)alertDeleteCancelAction
{
#warning verify translation of warning message! 1
#pragma mark TODO: verify translation of warning message! 1
	// open a alert with an OK and cancel button
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:(NSLocalizedString(@"GasView Delete this entry?",@"Delete this entry?"))
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"GasView Cancel",@"Cancel")) 
										  otherButtonTitles:(NSLocalizedString(@"GasView Yes, Delete",@"Yes, Delete"))
						  , nil];
	[alert show];
	[alert release];
}

 
- (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex == [alert cancelButtonIndex]) {
		return;
	}
	[self reallyDelete];
}

#pragma mark -
#pragma mark Setup the objects in use on this View

- (void)setGas:(Gas *)anotherGas {
	[gas release];
	gas = anotherGas;
	[gas retain];
}

- (NSDate *)dateValue {
	return dateValue;
}

- (void)setDateValue:(NSDate *)anotherDate {
	[dateValue release];
	dateValue = anotherDate;
	[dateValue retain];
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	NSString *title = [formatter stringFromDate:dateValue];
	[dateButton setTitle:title forState:UIControlStateNormal];
	[dateButton setTitle:title forState:UIControlStateHighlighted];
	[dateButton setTitle:title forState:UIControlStateSelected];
}

#pragma mark -

- (void)setBoxes {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	if (appDelegate.currentCar) { 
		self.navigationItem.title = appDelegate.currentCar.label;
	}
	[self setDateValue:[[appDelegate dateSelected] objectForKey:@"gasDate"]];
	NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
	NSString *title = [formatter stringFromDate:dateValue];
	[dateButton setTitle:title forState:UIControlStateNormal];
	[dateButton setTitle:title forState:UIControlStateHighlighted];
	[dateButton setTitle:title forState:UIControlStateSelected];
	odometerBox.text = [[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:gas.odometer]];
	[fuelLabel setText:[FuelLogAppDelegate pref].fuelText];
	fuelBox.text = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:gas.volume]];
	[dpfLabel setText:[FuelLogAppDelegate pref].dpfText];
	[self updateDpf];
	costBox.text = [[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:gas.cost]];
	fullTankSwitch.on = gas.full; 
	if (gas.pk == -1) {
		deleteButton.hidden = YES;
		odometerBox.clearsOnBeginEditing = TRUE;
		fuelBox.clearsOnBeginEditing = TRUE;
		costBox.clearsOnBeginEditing = TRUE;
		unitCostBox.clearsOnBeginEditing = TRUE;
		self.scrollView.contentSize = CGSizeMake(320, 520);// was 480px with text keyboard 
		//if ([FuelLogAppDelegate scanFloat:unitCostText.text] != 0.0) 
			[unitCostBox setText:@"0"];
	} else {
		deleteButton.hidden = NO;
		odometerBox.clearsOnBeginEditing = FALSE;
		fuelBox.clearsOnBeginEditing = FALSE;
		costBox.clearsOnBeginEditing = FALSE;
		unitCostBox.clearsOnBeginEditing = FALSE;
		self.scrollView.contentSize = CGSizeMake(320, 580);// allow to scroll up to see delete button
		[self updateUnitCost:99 userDidDecideOnWhichTextBoxToRecalc:NO];
	}
	self.accessCounterFuelBox = 0;
	self.accessCounterCostBox = 0;
	self.accessCounterUnitCostBox = 0;
}

/*
 // override if customizing
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
 // Initialization code
 }
 return self;
 }
 */

/*
 Implement loadView if you want to create a view hierarchy programmatically
 - (void)loadView {
 }
 */
#pragma mark -
#pragma mark UIView stuff

- (void)viewDidLoad { 
    [super viewDidLoad]; 
 doneButton = 	[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemSave 
															  target:self 
															  action:@selector(done:)];
	
	self.navigationItem.rightBarButtonItem = doneButton;
// # pragma mark TO DO: have set now in xib, check if still needed here
	[odometerBox addTarget:self action:@selector(updateTextFieldWithDecimalPlaces:) forControlEvents:UIControlEventEditingChanged];
	[fuelBox addTarget:self action:@selector(updateTextFieldWithDecimalPlaces:) forControlEvents:UIControlEventEditingChanged];
	[costBox addTarget:self action:@selector(updateTextFieldWithDecimalPlaces:) forControlEvents:UIControlEventEditingChanged];
	[unitCostBox addTarget:self action:@selector(updateTextFieldWithDecimalPlaces:) forControlEvents:UIControlEventEditingChanged];
	
	[self.dateButton useSystemTouchStyle]; 
	[self.deleteButton useRedDeleteStyle]; 
	[self.fuelVolumeChangedButton useGreenConfirmStyle];
	[self.costChangedButton useGreenConfirmStyle];
	[self.unitCostChangedButton useGreenConfirmStyle];
	
	fuelVolumeChangedButton.hidden = YES;
 	costChangedButton.hidden = YES;
	unitCostChangedButton.hidden = YES;	
	isOkToUpdate = NO;
	areUpdatesPending = NO; // obsolete, take out eventually
	self.askingButtonsAreHidden = YES;
}

- (void)viewDidUnload {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil; 	
}


- (void)viewWillAppear:(BOOL)animated {
    keyboardIsShown = NO;
	
	[super viewWillAppear:animated];
	[self.navigationController setToolbarHidden:YES animated:YES];
	[self setBoxes];
}

- (void)viewWillDisappear:(BOOL)animated {
	[self.navigationController setToolbarHidden:NO animated:YES];
	self.accessCounterFuelBox = 0;
	self.accessCounterCostBox = 0;
	self.accessCounterUnitCostBox = 0;
	self.askingButtonsAreHidden = YES;
	
	fuelVolumeChangedButton.hidden = YES;
 	costChangedButton.hidden = YES;
	unitCostChangedButton.hidden = YES;	
	isOkToUpdate = NO; 
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
	[unitCostBox resignFirstResponder];
	
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[dateController release];
	[scrollView release];	
	[doneButton release];
	[gas release];
	[dateButton release];
	[odometerBox release];
	[fuelLabel release];
	[fuelBox release];
	[dpfLabel release];
	[dpfText release];
	[costBox release];
	[unitCostText release];
	[unitCostBox release];
	[deleteButton release];
	[fullTankSwitch release];
	[dateValue release]; 
	[super dealloc];
}
#pragma mark -
#pragma mark Done with Setup, check user inputs now

- (void)alertFail:(NSString *)errorMessageToDisplay {
	// open a alert with an OK
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" 
													message:errorMessageToDisplay
												   delegate:self 
										  cancelButtonTitle:(NSLocalizedString(@"Login_alertFail OK",@"OK")) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];
}



- (IBAction)done:(id)sender {
	float distance = [FuelLogAppDelegate scanFloat:odometerBox.text];
	float fuel = [FuelLogAppDelegate scanFloat:fuelBox.text];
	float cost = [FuelLogAppDelegate scanFloat:costBox.text];

	if (distance <= 0) {
		[self alertFail:(NSLocalizedString(@"GasView Odometer",@"Odometer must be a positive number.")) ];
		return;
	}
	if (fuel <= 0) {
		[self alertFail:(NSLocalizedString(@"GasView Fuel",@"Fuel volume must be a positive number.")) ];
		return;
	}
	if (cost < 0) {
		[self alertFail:(NSLocalizedString(@"GasView Cost",@"Cost must be a positive number.")) ];
		return;
	}
 
#warning  verify translation of warning message! 2
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	Gas *lastPump = [appDelegate findPreviousGasEntry:dateValue odometer:distance];
	if (lastPump && (gas.pk == -1 || gas.pk != lastPump.pk)) {
		if (distance < lastPump.odometer) {
			[self alertFail:[NSString stringWithFormat:(NSLocalizedString(@"GasView Odometer lower",@"Odometer is lower than previous value of %.1f")), lastPump.odometer]];
			return;
		} else if ([dateValue compare:lastPump.date] == NSOrderedAscending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *lastDate = [formatter stringFromDate:lastPump.date];			
			[self alertFail:[NSString stringWithFormat:(NSLocalizedString(@"GasView Date earlier",@"Date is earlier than previous fuel date of %@")), lastDate]];
			return;
		}
	}
	Gas *nextPump = [appDelegate findNextGasEntry:dateValue odometer:distance];
	if (nextPump && (gas.pk == -1 || gas.pk != nextPump.pk)) { 
		if (distance > nextPump.odometer) {
			[self alertFail:[NSString stringWithFormat:(NSLocalizedString(@"GasView Odometer higher",@"Odometer is higher than next value of %.1f")), lastPump.odometer]];
			return;
		} else if ([dateValue compare:nextPump.date] == NSOrderedDescending) {
			NSDateFormatter *formatter = [FuelLogAppDelegate pref].dateFormatter;
			NSString *nextDate = [formatter stringFromDate:nextPump.date];
			[self alertFail:[NSString stringWithFormat:(NSLocalizedString(@"GasView Date later",@"Date is later than next fuel date of %@")), nextDate]];
			return;
		}
	} 
	[gas setDate:dateValue];
	[gas setOdometer:distance];
	[gas setVolume:fuel];
	[gas setCost:cost];
	[gas setFull:fullTankSwitch.on]; 
	[appDelegate addGasIfNeeded:gas previous:lastPump next:nextPump];
	[gas release];
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
//	[self dismissModalViewControllerAnimated:YES];
	[self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)cancel:(id)sender { 
	[gas release];
	[odometerBox resignFirstResponder];
	[fuelBox resignFirstResponder];
	[costBox resignFirstResponder];
	[self.navigationController popViewControllerAnimated:YES];
//	[self dismissModalViewControllerAnimated:YES];
}

- (IBAction)deleteEntry:(id)sender {
	[self alertDeleteCancelAction];
}

- (void)reallyDelete {
	if (gas.pk != -1) {
		FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
		[appDelegate removeGas:gas];
	}
	[self cancel:nil];
}

- (IBAction)editDate:(id)sender {
// *
	if (dateController == nil) {
		dateController = [[DateViewController alloc] initWithNibName:@"Date" bundle:nil];
	}
//*/
//	DateViewController *dateController = [FuelLogViewController dateViewController]; 

 	[dateController setEditedFieldKey:@"gasDate"];
	[dateController setText:(NSLocalizedString(@"GasView datesubscreen",@"Date"))]; 
	[dateController setDateValue:dateValue];
//	dateValue = [dateController dateValue];
	UIBarButtonItem *newBackButton = [[UIBarButtonItem alloc] 
									  initWithTitle:  (NSLocalizedString(@"Cancel", @"")) 
									  style: UIBarButtonItemStyleBordered 
									  target: nil 
									  action: nil];
	[self.navigationItem setBackBarButtonItem: newBackButton];
	[self.navigationController setToolbarHidden:YES animated:NO];
	[self.navigationController pushViewController:dateController animated:YES];
	[newBackButton release]; 

	//	[self presentModalViewController:dateController animated:YES];
}

#pragma mark -
#pragma mark TextField stuff
// 
/*  
 
-(BOOL)textFieldShouldBeginEditing:(UITextField *)theTextField
{
	CGSize keyboardSizeHardCoded = CGSizeMake(320,212);
	keyboardSize = keyboardSizeHardCoded;
	CGRect viewFrame = [scrollView frame];
	memorisedViewOrigin = viewFrame;
	//	CGRect textFieldRect = [activeField frame]; // was: from when KbShowNotification was used
	CGRect textFieldRect = [theTextField frame];

	float deltaToMove = ((float)textFieldRect.origin.y + (float)textFieldRect.size.height) //location bottom edge of active filed
	- (viewFrame.size.height - keyboardSize.height); // upper edge keyboard
	if (deltaToMove >= 0) {
		viewFrame.origin.y -= deltaToMove + 5;
		self.scrollView.frame = viewFrame; // keep setContentsize in next line commented

//		self.scrollView.contentSize = CGSizeMake(self.scrollView.contentSize.width, self.scrollView.contentSize.height + deltaToMove);
	//	debug(@"self.scrollView.contentSize %@",self.scrollView.contentSize);
		[UIView beginAnimations:nil context:NULL];
		//		[UIView setAnimationBeginsFromCurrentState:YES]; 
		//		[UIView setAnimationDelegate:self];
		[UIView setAnimationDuration:0.5f];		
		[scrollView scrollRectToVisible:textFieldRect animated:YES];
		[UIView commitAnimations];
	}  
	return YES;
}	
 

// */
//
/*
- (BOOL)textFieldShouldBeginEditing:(UITextField *)theTextField {
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.5f];		
	[scrollView scrollRectToVisible:theTextField.bounds animated:YES];
	[UIView commitAnimations];
	return YES;
}
 // */
-(void)textFieldDidBeginEditing:(UITextField *)theTextField
{
	if (!self.askingButtonsAreHidden) {
		fuelVolumeChangedButton.hidden = YES;
		costChangedButton.hidden = YES;
		unitCostChangedButton.hidden = YES;	 
		isOkToUpdate = NO;
		self.askingButtonsAreHidden = YES;
	}
	
	activeField = theTextField;
}

// */

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField { 
	float val = [FuelLogAppDelegate scanFloat:theTextField.text];
	if (val == 0) {
		theTextField.text = @"";
		return NO;
	}
	[theTextField resignFirstResponder];
	if (theTextField == odometerBox) {
		//	gas.odometer = val;
		odometerBox.text = [[FuelLogAppDelegate pref].distanceFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
		odometerBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == fuelBox) {
		//	gas.volume = val;
		if (![fuelBox.text isEqualToString:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:val]] ]) 
		{
			fuelBox.text = [[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
			[self updateUnitCost:_kFuel userDidDecideOnWhichTextBoxToRecalc:NO];
		}
		fuelBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == costBox) {
		//	gas.cost = val;
		if (![costBox.text isEqualToString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:val]]])
		{
			costBox.text = [[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
			[self updateUnitCost:_kCost userDidDecideOnWhichTextBoxToRecalc:NO];
		}
		costBox.clearsOnBeginEditing = FALSE; 
		
	}else if (theTextField == unitCostBox) {
		if (![unitCostBox.text isEqualToString:[[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:val]]])
		{
			unitCostBox.text = [[FuelLogAppDelegate pref].costFormatter stringFromNumber:[NSNumber numberWithFloat:val]];
			[self updateUnitCost:_kUnit userDidDecideOnWhichTextBoxToRecalc:NO]; 
		}		unitCostBox.clearsOnBeginEditing = FALSE;
	}
	return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)theTextField {
	if (theTextField == odometerBox) {
		odometerBox.clearsOnBeginEditing = FALSE;
	} else if (theTextField == fuelBox) {
		fuelBox.clearsOnBeginEditing = FALSE;
		//		++accessCounterFuelBox;
	} else if (theTextField == costBox) {
		costBox.clearsOnBeginEditing = FALSE;
		//		++accessCounterCostBox;
	} else if (theTextField == unitCostBox) {
		unitCostBox.clearsOnBeginEditing = FALSE;
		//		++accessCounterUnitCostBox;
	}
	activeField = nil;
	
}

-(BOOL) textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range 
replacementString:(NSString*)textEntered {
	//	debug(@"in shouldChangeCharactersInRange");
	NSCharacterSet * myCharSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789,."];
	for (int i = 0; i < [textEntered length]; i++) 
	{
		unichar c = [textEntered characterAtIndex:i];
		if (![myCharSet characterIsMember:c]) 	return NO;
	} 
	return YES;
}	

/*
 when textfied is created:
 [textField addTarget:self action:@selector(updateTextFieldWithDecimalPlaces:) forControlEvents:UIControlEventEditingChanged];
 
 */

- (void)updateTextFieldWithDecimalPlaces:(UITextField *)theTextField{
	Pref *pref = [FuelLogAppDelegate pref];
	NSNumberFormatter *currentFormatter = [[NSNumberFormatter alloc] init];
	int currentDigits = 0;
	int divisor = 1;
	if (theTextField == odometerBox) {
		currentDigits = pref.odometerDigits;
		currentFormatter = [[FuelLogAppDelegate pref].distanceFormatter retain];
	} else if (theTextField == fuelBox) {
		currentDigits = pref.volumeDigits;
		currentFormatter = [[FuelLogAppDelegate pref].volumeFormatter retain];
	} else if (theTextField == costBox) {
		currentDigits = 2;
		currentFormatter = [[FuelLogAppDelegate pref].costFormatter retain];
	} else if (theTextField == unitCostBox) {
		currentDigits = 3; //pref.unitCostDigits;
		currentFormatter = [[FuelLogAppDelegate pref].unitCostFormatter retain];
#pragma mark TODO: define unitCost formatter
 	}
	divisor = pow( 10, currentDigits);
	NSString * formatString = [NSString stringWithString:@"%0."];
	formatString = [formatString stringByAppendingString:[NSString stringWithFormat:@"%d",currentDigits]];
	formatString = [formatString stringByAppendingString:@"f"];
	
	static BOOL toggle = NO;
	if (toggle) {
		toggle = NO;
		return;
	}
	
	NSString* strPrice = [theTextField  text];
	strPrice = [strPrice stringByReplacingOccurrencesOfString:@"." withString:@""];
	strPrice = [strPrice stringByReplacingOccurrencesOfString:@"," withString:@""];
	toggle = YES;
	NSString *s0 = [currentFormatter stringFromNumber:[NSNumber numberWithFloat:[strPrice floatValue]/divisor]];
	theTextField.text = s0;
	//[@"" stringByAppendingFormat:formatString, [strPrice floatValue]/divisor];
	[currentFormatter release];
}

#pragma mark -
/*- (void)scrollViewWillBeginDragging:(UIScrollView *)myScrollView {
	NSLog(@"scrollViewWillBeginDragging Content offset %f", myScrollView.contentOffset.y);
}

- (void)scrollViewDidScroll:(UIScrollView *)myScrollView {
//	NSLog(@"scrollViewDidScroll Content offset %f", (CGFloat ) scrollView.contentOffset.y);
 
}
*/

- (void)scrollViewDidEndDragging:(UIScrollView *)myScrollView willDecelerate:(BOOL)decelerate {
	if (myScrollView.contentOffset.y > 100.0f) {
		[odometerBox resignFirstResponder];
		[fuelBox resignFirstResponder];
		[costBox resignFirstResponder];
		[unitCostBox resignFirstResponder];
	//	self.scrollView.frame.origin.y = self.scrollView.frame.origin.y - 5.0f;
		NSLog(@"scrollViewDidEndDragging Content offset %f", myScrollView.contentOffset.y);
	}

	
}

#pragma mark -
#pragma mark ChangeHandlers

- (IBAction)odometerChanged:(id)sender {
	[self updateDpf];
}

- (IBAction)fuelChanged:(id)sender {
	[self updateDpf];
	[self updateUnitCost:_kFuel userDidDecideOnWhichTextBoxToRecalc:NO];
}

- (IBAction)costChanged:(id)sender {
	[self updateUnitCost:_kCost userDidDecideOnWhichTextBoxToRecalc:NO];
}

- (IBAction)unitCostChanged:(id)sender {
	[self updateUnitCost:_kUnit userDidDecideOnWhichTextBoxToRecalc:NO];
}


- (void)updateDpf {
	FuelLogAppDelegate *appDelegate = (FuelLogAppDelegate *)[[UIApplication sharedApplication] delegate];
	float odometer = [FuelLogAppDelegate scanFloat:odometerBox.text];
	float fuel = [FuelLogAppDelegate scanFloat:fuelBox.text];
	float dpf = [appDelegate gasEconomy:gas.pk odometer:odometer fuel:fuel];
	int prefUnits = [FuelLogAppDelegate pref].units;
	if (dpf > 0.0 &&  prefUnits == INV_METRIC) {
		dpf = 100.0 / dpf;
	} else if (dpf > 0.0 && prefUnits == NORWAY) {
		dpf = 10.0 / dpf;
	} else if (prefUnits == UK) {
		dpf = dpf * UK_GALLON;
	}
	if (dpf > 0.0) 
		[dpfText setText:[[FuelLogAppDelegate pref].volumeFormatter stringFromNumber:[NSNumber numberWithFloat:dpf]]];
	else 
		[dpfText setText:@"---"];
}
#pragma mark -

- (IBAction)tappedFuelVolumeChangedButton{ 
	fuelVolumeChangedButton.hidden = YES;
 	costChangedButton.hidden = YES;
	unitCostChangedButton.hidden = YES;	 
	isOkToUpdate = TRUE;
	self.askingButtonsAreHidden = YES;
	self.accessCounterFuelBox = 0;
	self.accessCounterCostBox = 2;
	self.accessCounterUnitCostBox = 2;
	[self updateUnitCost:_kFuel userDidDecideOnWhichTextBoxToRecalc:YES];
}

- (IBAction)tappedCostChangedButton{
	fuelVolumeChangedButton.hidden = YES;
 	costChangedButton.hidden = YES;
	unitCostChangedButton.hidden = YES;	 
	isOkToUpdate = TRUE;
	self.askingButtonsAreHidden = YES;
	self.accessCounterFuelBox = 2;
	self.accessCounterCostBox = 0;
	self.accessCounterUnitCostBox = 2;
	[self updateUnitCost:_kCost userDidDecideOnWhichTextBoxToRecalc:YES];
}

- (IBAction)tappedUnitCostChangedButton {
	fuelVolumeChangedButton.hidden = YES;
 	costChangedButton.hidden = YES;
	unitCostChangedButton.hidden = YES;	 
	isOkToUpdate = TRUE;
	self.askingButtonsAreHidden = YES;
	self.accessCounterFuelBox = 2;
	self.accessCounterCostBox = 2;
	self.accessCounterUnitCostBox = 0;
	[self updateUnitCost:_kUnit userDidDecideOnWhichTextBoxToRecalc:YES];
}

- (void)activateQuestionButtonsAfterValuesModify:(int)boxIndexUpdated  { 
	if ((gas.pk != -1) && areUpdatesPending && self.askingButtonsAreHidden){
		switch (boxIndexUpdated) {
			case _kFuel:
				//				[self.fuelVolumeChangedButton setHidden:NO];
				[self.costChangedButton setHidden:NO];
				[self.unitCostChangedButton setHidden:NO];
				//	[fuelVolumeChangedButton setTitle:@"<=" forState:UIControlStateNormal];
				[costChangedButton       setTitle:@"?"  forState:UIControlStateNormal];
				[unitCostChangedButton   setTitle:@"?"  forState:UIControlStateNormal];
				break;
			case _kCost:
				[self.fuelVolumeChangedButton setHidden:NO];
				//				[self.costChangedButton setHidden:NO];
				[self.unitCostChangedButton setHidden:NO];
				[fuelVolumeChangedButton setTitle:@"?" forState:UIControlStateNormal];
				//	[costChangedButton       setTitle:@"<="  forState:UIControlStateNormal];
				[unitCostChangedButton   setTitle:@"?"  forState:UIControlStateNormal];
				break;
			case _kUnit:
				[self.fuelVolumeChangedButton setHidden:NO];
				[self.costChangedButton setHidden:NO];
				//				[self.unitCostChangedButton setHidden:NO];
				[fuelVolumeChangedButton setTitle:@"?" forState:UIControlStateNormal];
				[costChangedButton       setTitle:@"?"  forState:UIControlStateNormal];
				//	[unitCostChangedButton   setTitle:@"<="  forState:UIControlStateNormal];
				break;
			default:
				break;
		}
		// do the calc here because the button  keep appearing to low 
		int distance = 15;
		int widthAndHeight = 27;
		CGRect boxFrame = fuelBox.frame;
		
		boxFrame.origin.x = boxFrame.origin.x + boxFrame.size.width + distance;
		boxFrame.origin.y = boxFrame.origin.y -(( boxFrame.size.height -widthAndHeight)/2); 
		boxFrame.size.width = widthAndHeight;
		boxFrame.size.height = widthAndHeight;
		fuelVolumeChangedButton.frame = boxFrame;
		
		boxFrame = costBox.frame;
		boxFrame.origin.x = boxFrame.origin.x + boxFrame.size.width + distance;
		boxFrame.origin.y = boxFrame.origin.y + (( boxFrame.size.height -widthAndHeight)/2); 
		boxFrame.size.width = widthAndHeight;
		boxFrame.size.height = widthAndHeight;
		costChangedButton.frame = boxFrame;
		
		boxFrame = unitCostBox.frame;
		boxFrame.origin.x = boxFrame.origin.x + boxFrame.size.width + distance;
		boxFrame.origin.y = boxFrame.origin.y + (( boxFrame.size.height -widthAndHeight)/2) ;
		boxFrame.size.width = widthAndHeight;
		boxFrame.size.height = widthAndHeight;
		unitCostChangedButton.frame = boxFrame;
		
		self.askingButtonsAreHidden = NO;
	}
}


- (void)updateUnitCost:(int)boxIndexUpdated userDidDecideOnWhichTextBoxToRecalc:(BOOL)userDidDecideOnWhichTextBoxToRecalc {  	areUpdatesPending = YES;
	switch (boxIndexUpdated) {
		case _kFuel:
			self.accessCounterFuelBox += 1; 
			if (!userDidDecideOnWhichTextBoxToRecalc)  [self activateQuestionButtonsAfterValuesModify:boxIndexUpdated];
			break;
		case _kCost:
			self.accessCounterCostBox += 1; 
			if (!userDidDecideOnWhichTextBoxToRecalc) [self activateQuestionButtonsAfterValuesModify:boxIndexUpdated];
			break;
		case _kUnit:
			self.accessCounterUnitCostBox += 1; 
			if (!userDidDecideOnWhichTextBoxToRecalc)  [self activateQuestionButtonsAfterValuesModify:boxIndexUpdated];
			break;
		case 99:
			isOkToUpdate = YES;
			break;
		default:
			break;
	}
	
	if ((gas.pk == -1) || isOkToUpdate) {
		float fuelVolume = [FuelLogAppDelegate scanFloat:fuelBox.text];
		float fuelCost = [FuelLogAppDelegate scanFloat:costBox.text];
		float unitCost = [FuelLogAppDelegate scanFloat:unitCostBox.text];
		if ((self.accessCounterFuelBox > self.accessCounterUnitCostBox &&
			 self.accessCounterCostBox > self.accessCounterUnitCostBox) || 	//user entered FuelBox and CostBox, calc UnitCost
			boxIndexUpdated == 99 ) // we are beng called from SetBoxes at first time View load
		{
			if (fuelVolume > 0.0) {
				if(fuelCost > 0.0) {
					float unitCost = fuelCost/fuelVolume;
					NSNumberFormatter *unitCostFormatter = [FuelLogAppDelegate pref].unitCostFormatter;
					[unitCostBox setText:[unitCostFormatter stringFromNumber:[NSNumber numberWithFloat:unitCost]]];
				} 
			}
		}
		// =======
		if (self.accessCounterFuelBox > self.accessCounterCostBox &&
			self.accessCounterUnitCostBox > self.accessCounterCostBox)   	//user entered FuelBox and UnitCost, calc CostBox
		{
			if (fuelVolume > 0.0) {
				if(unitCost > 0.0) {
					float cost = fuelVolume * unitCost;
					NSNumberFormatter * costFormatter = [FuelLogAppDelegate pref].costFormatter;
					[costBox setText:[costFormatter stringFromNumber:[NSNumber numberWithFloat:cost]]];
				} 
			} 
		}
		// =======	
		if (self.accessCounterCostBox > self.accessCounterFuelBox &&
			self.accessCounterUnitCostBox > self.accessCounterFuelBox)   	//user entered CostBox and UnitCost, calc FuelBox
		{
			if (fuelCost > 0.0) {
				if(unitCost > 0.0) {
					float fuelVolume = fuelCost / unitCost;
					NSNumberFormatter * volumeFormatter = [FuelLogAppDelegate pref].volumeFormatter;
					[fuelBox setText:[volumeFormatter stringFromNumber:[NSNumber numberWithFloat:fuelVolume]]];
				} 
			} 
		}
		areUpdatesPending = NO;
		isOkToUpdate = NO;
	} 
	
	
}



@end
